package com.zjy.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.zjy.dao.role.RoleDaoImpl;
import com.zjy.pojo.Role;
import com.zjy.pojo.User;
import com.zjy.service.role.RoleService;
import com.zjy.service.role.RoleServiceImpl;
import com.zjy.service.user.UserService;
import com.zjy.service.user.UserServiceImpl;
import com.zjy.util.Constants;
import com.zjy.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//实现Servlet复用
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=req.getParameter("method");

        if(method.equals("savepwd")&&method!=null){
            this.updatePwd(req,resp);
        }else if(method.equals("pwdmodify")&&method!=null){
            this.pwdModify(req, resp);
        }else if(method.equals("query")&&method!=null){
            this.query(req, resp);
        }else if(method.equals("add")&&method!=null){
            this.add(req,resp);
        }else if(method.equals("deluser")&&method!=null){
            this.delUser(req,resp);
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        Object user = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");
        Boolean flag=false;
        if(user!=null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService=new UserServiceImpl();
            flag = userService.updatePwd(((User) user).getId(), newpassword);
            if(flag){
                req.setAttribute("message","修改密码成功，请退出，使用新密码登录");
                //密码修改成功，移除session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute("message","密码修改失败");
            }

        }else{
            req.setAttribute("message","新密码不合格");

        }

        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //验证旧密码，session里面有用户的密码，不用从数据库中比较，提高效率
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从session里面拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //万能的map:结果集
        HashMap<String, String> resultMap = new HashMap<String, String>();

        //与js页面的内容相对应
        if(o==null){//session失效，session过期

            resultMap.put("result","sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//输入的密码为空
            resultMap.put("result","error");
        }else {
            //session中用户的密码
            String userPassword = ((User) o).getUserPassword();
            if(oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
        }
        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(resultMap.get("result"));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    //获得用户列表信息
    public void query(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String queryUserName=req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        //输入的第几页跳转
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole=0;//下拉框默认第一个为0
        UserService userService = new UserServiceImpl();
        List<User> userList=null;
        //设置页面容量
        int pageSize=Constants.pageSize;
        //当前页码
        int currentPageNo=1;
        System.out.println("queryUserName servlet--------"+queryUserName);
        System.out.println("queryUserRole servlet--------"+queryUserRole);
        System.out.println("query pageIndex--------- > " + pageIndex);

        if(queryUserName==null){
            queryUserName="";
        }
        if(temp!=null && !temp.equals("")){
            queryUserRole=Integer.parseInt(temp);
        }
        if(pageIndex!=null){
            try{
                currentPageNo=Integer.valueOf(pageIndex);
            }catch (NumberFormatException e){
                resp.sendRedirect("error.jsp");
            }

        }
        //总数量（表）
        int totalCount=userService.getUserCount(queryUserName,queryUserRole);
        //总页数,用到了给定的工具类
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);

        int totalPageCount=pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo<1){
            currentPageNo=1;
        } else if(currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;
        }

        userList=userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
        req.setAttribute("userList",userList);
        List<Role> roleList=null;
        RoleService roleService = new RoleServiceImpl();
        roleList=roleService.getRoleList();


        req.setAttribute("roleList",roleList);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);

        req.getRequestDispatcher("userlist.jsp").forward(req,resp);
    }
    //添加用户
    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("进入添加用户add()--------");
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user=new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-mm-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());

        UserService userService = new UserServiceImpl();
        if(userService.add(user)){
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else {
            req.getRequestDispatcher("useradd.jsp").forward(req,resp);
        }

    }
    //删除用户
    private void delUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id=req.getParameter("uid");
        System.out.println("id=========:"+id);
        Integer delId=0;
        try{
            delId=(Integer)Integer.parseInt(id);
        }catch (Exception e){
            delId=99999;
        }
        System.out.println("delId:   "+delId);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(delId<=0){
            resultMap.put("delResult","notexist");
        }else{
            UserService userService = new UserServiceImpl();
            if(userService.delUser(delId)){
                resultMap.put("delResult","true");
            }else{
                resultMap.put("delResult","false");
            }
        }
        //把resultMap转换成json对象输出  用到了fastjson包
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();


    }







}
